// pages/orderRecord/orderRecord.js
const app = getApp()
let request = require("../../utils/request.js");
let flag = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    windowHeight: 0,
    scrollViewHeight: 0,
    currentPage: 1,
    dataArray: [],
    hasNextList: false,
    StopInfoCurrentPage: 1,
    StopInfoPageSize: 10,
    isCanNext: true,
    verifyLoginDialog: false,
    titleText: '我的欠费',
    tradeType: '',
    orderStatus: 1,
    tabs: [{
      id: 1,
      name: '待支付',
      select: true
    },
    {
      id: 2,
      name: '已完成',
      select: false
    }],
    tabIndex: 0,
    articlesing: [],
    orderInfo:{}, //上次订单信息
    orderState:false,   //上一次的订单信息

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    that.setData({
      tradeType: options.type
    })
    if (options.type == 3) {
      that.setData({
        titleText: '余额支付订单'
      })
    }
    // 先取出页面高度 windowHeight
    that.setData({
      windowHeight: wx.getSystemInfoSync().windowHeight
    });
    let scrollViewHeight = that.data.windowHeight - that.data.statusBarHeight - 44 - 27;
    that.setData({
      scrollViewHeight: scrollViewHeight
    })
    let token = wx.getStorageSync('token');
    if (token) {
      this.getParkStopInfo()
    } else {
      this.setData({
        verifyLoginDialog: true
      })
    }
    this.orderInfo()
  },
  verifyLogin() {
    this.getParkStopInfo()
  },

  //未交费订单信息
  orderInfo(){
    request.http('/order/info-trade-record/get-arrears-order', 'GET', {}).then(res => {
      let data = res.data.data;
      if (res.data.code == 200) {
        if(data.length != 0){
          console.log(data);
          this.setData({
            orderInfo : data[0],
            orderState: true
          })
          console.log('订单信息',this.data.orderInfo);
        }
      }
    }).catch(err => { console.error(err) })
  },

  /**
   * 支付
   */
  payment() {
    let _this = this
    let orderData = this.data.orderInfo;
    //  支付垫付停车费
    let params = {
      totalAmount: orderData.paidAmount,     //实付金额
      tradeRecordId: orderData.id,    // 订单id
    }
    request.http('/order/info-trade-record/pay-behalf', 'POST', params , 0)
      .then(res => {
        console.log(res)
        if (res.data.code == 200) {
          let orderCode = res.data.data.orderCode
          //支付
          wx.requestPayment({
            timeStamp: res.data.data.timeStamp, // 时间戳，必填（后台传回）
            nonceStr: res.data.data.nonceStr, // 随机字符串，必填（后台传回）
            package: res.data.data.package, // 统一下单接口返回的 prepay_id 参数值，必填（后台传回）
            signType: 'MD5', // 签名算法，非必填，（预先约定或者后台传回）
            paySign: res.data.data.paySign, // 签名 ，必填 （后台传回）
            success: function (res) { // 成功后的回调函数
              wx.showToast({ title: '支付成功' })
              setTimeout(function () {
                _this.setData({ orderState: false })
              }, 2000) 
            },
            fail(res) {
              console.log(res)
            }
          })
        } else {
          wx.showToast({ title: res.data.desc })
        }
      })
  },
  /**
   * 获取用户订单
   */
  getParkStopInfo(next) {
    let that = this
    let url = '/order/orderInfo/getCustomerOrderPage'
    let params = {
      currentPage: that.data.StopInfoCurrentPage,
      pageSize: that.data.StopInfoPageSize,
      tradeType: that.data.tradeType,
      orderStatus: that.data.orderStatus
    }
    request.http(url, 'POST', params, 0)
      .then(res => {
        if (res.data.code == 200) {
          if (next && res.data.data.records.length <= 0) {
            that.setData({
              isCanNext: false
            })
          } else if (next) {
            if (that.data.orderStatus == 1) {
              let articlesing = that.data.articlesing
              articlesing = articlesing.concat(res.data.data.records)
              that.setData({
                articlesing: articlesing
              }) 
            } else {
              let articles = that.data.articles
              articles = articles.concat(res.data.data.records)
              that.setData({
                articles: articles
              }) 
            }
          } else {
            if (that.data.orderStatus == 1) {
              that.setData({
                articlesing: res.data.data.records
              })
              // console.log('进行中订单',this.data.articlesing);
            } else {
              that.setData({
                articles: res.data.data.records
              })
              // console.log('已完成订单',this.data.articles);
            }
          }
          flag = false
        }
      })
  },
  /**
   * 滚动条滚动到底部触发
   */
  scrollLower: function () {
    if (flag) {
      return
    }
    flag = true
    this.setData({
      StopInfoCurrentPage: this.data.StopInfoCurrentPage + 1
    })
    if (this.data.isCanNext) {
      this.getParkStopInfo(true)
    }
  },

  // 复制订单号
  copyOrderCode(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.copy,
      success(res) {
        console.log(res);
      }
    })
  },
  /**
   * 切换tab
   * @param {*} e 
   */
  selectTab(e) {
    let index = e.target.dataset.index;
    let that = this;
    let tabs = that.data.tabs;
    for (let i = 0; i < tabs.length; i++) {
      if (i == index) {
        tabs[i].select = true
      } else {
        tabs[i].select = false;
      }
    }
    that.setData({
      tabIndex: index,
      tabs: tabs
    })
  },
  bindchange(e) {
    let index = e.detail.current
    let tabs = this.data.tabs;
    for (let i = 0; i < tabs.length; i++) {
      if (i == index) {
        tabs[i].select = true
      } else {
        tabs[i].select = false;
      }
    }
    this.setData({
      tabIndex: index,
      tabs: tabs,
      orderStatus: tabs[index].id,
      StopInfoCurrentPage: 1,
      isCanNext: true
    })
    this.getParkStopInfo()
  },
})